<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">用户管理</h1>
        <p class="page-desc">管理系统用户，包括用户信息、权限和状态管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          新建用户
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <div class="table-container">
      <el-table :data="userList" v-loading="loading">
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              {{ row.nickname || row.username }}
            </el-avatar>
          </template>
        </el-table-column>
        
        <el-table-column prop="username" label="用户名" width="120" />
        
        <el-table-column prop="nickname" label="昵称" width="120" />
        
        <el-table-column prop="email" label="邮箱" min-width="180" />
        
        <el-table-column prop="phone" label="手机号" width="130" />
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginTime" label="最后登录" width="160">
          <template #default="{ row }">
            {{ row.lastLoginTime ? formatDate(row.lastLoginTime) : '从未登录' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleResetPassword(row)">
              重置密码
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #f56c6c"
              @click="handleDelete(row)"
              v-if="row.id !== userStore.userInfo?.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            :disabled="isEdit"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="头像" prop="avatar">
          <div class="avatar-upload">
            <el-avatar :src="form.avatar" :size="80" v-if="form.avatar">
              {{ form.nickname || form.username }}
            </el-avatar>
            <div class="avatar-placeholder" v-else>
              <el-icon><User /></el-icon>
            </div>
            <div class="avatar-actions">
              <el-button size="small" @click="selectAvatar">选择头像</el-button>
              <el-button size="small" type="danger" @click="removeAvatar" v-if="form.avatar">
                删除
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { User } from '@/types/api'

const userStore = useUserStore()

const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  status: undefined as number | undefined,
})

// 用户列表
const userList = ref<User[]>([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
})

// 表单数据
const form = ref<Partial<User>>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  status: 1,
})

// 表单验证规则
const formRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 100, message: '密码长度在 6 到 100 个字符', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新建用户')

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true
    // TODO: 调用用户列表API
    // const response = await userApi.getUserPage({
    //   current: pagination.current,
    //   size: pagination.size,
    //   ...searchForm,
    // })
    
    // 模拟数据
    userList.value = [
      {
        id: 1,
        username: 'admin',
        nickname: '管理员',
        email: 'admin@lightcms.com',
        phone: '13800138000',
        avatar: '',
        status: 1,
        lastLoginTime: new Date().toISOString(),
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: new Date().toISOString(),
      },
      {
        id: 2,
        username: 'editor',
        nickname: '编辑',
        email: 'editor@lightcms.com',
        phone: '13800138001',
        avatar: '',
        status: 1,
        lastLoginTime: '2024-01-15T10:30:00Z',
        createdAt: '2024-01-02T00:00:00Z',
        updatedAt: '2024-01-15T10:30:00Z',
      },
    ]
    pagination.total = 2
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  getUserList()
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    status: undefined,
  })
  pagination.current = 1
  getUserList()
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: User) => {
  isEdit.value = true
  form.value = { ...row }
  delete form.value.password // 编辑时不显示密码
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: User) => {
  ElMessageBox.confirm(`确定要删除用户"${row.username}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // TODO: 调用删除用户API
      // await userApi.deleteUser(row.id)
      ElMessage.success('删除成功')
      getUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: User) => {
  try {
    // TODO: 调用更新用户状态API
    // await userApi.updateUserStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 处理重置密码
const handleResetPassword = (row: User) => {
  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputValidator: (value) => {
      if (!value || value.length < 6) {
        return '密码长度不能少于6位'
      }
      return true
    },
  }).then(async ({ value }) => {
    try {
      // TODO: 调用重置密码API
      // await userApi.resetPassword(row.id, value)
      ElMessage.success('密码重置成功')
    } catch (error) {
      console.error('重置密码失败:', error)
    }
  })
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      // TODO: 调用更新用户API
      // await userApi.updateUser(form.value.id!, form.value)
      ElMessage.success('更新成功')
    } else {
      // TODO: 调用创建用户API
      // await userApi.createUser(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    username: '',
    password: '',
    nickname: '',
    email: '',
    phone: '',
    avatar: '',
    status: 1,
  }
  formRef.value?.resetFields()
}

// 选择头像
const selectAvatar = () => {
  // TODO: 打开文件选择器
  ElMessage.info('文件选择功能待实现')
}

// 删除头像
const removeAvatar = () => {
  form.value.avatar = ''
}

// 处理分页大小变更
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getUserList()
}

// 处理当前页变更
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getUserList()
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped lang="scss">
.user-management {
  padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .header-left {
      .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
        margin: 0 0 6px 0;
      }

      .page-desc {
        font-size: 14px;
        color: #6c757d;
        margin: 0;
      }
    }

    .header-right {
      .add-btn {
        height: 40px;
        padding: 0 20px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 6px;
      }
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .avatar-upload {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .avatar-placeholder {
      width: 80px;
      height: 80px;
      border: 2px dashed #dcdfe6;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #c0c4cc;
      font-size: 24px;
    }
    
    .avatar-actions {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
  }
}
</style>
